package com.xiaohao.communication.ESutils;

import lombok.Data;
import lombok.extern.java.Log;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.io.IOException;

/*
 *
 * 滚动构造类
 *
 * */

@Log
@Component
@Data
public class ScrollProcessor {

    public SearchResponse scrollToNext(@NotNull RestHighLevelClient client,
                                       @NotNull String scrollId,
                                       @NotNull Scroll scroll) throws IOException {

        SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
        scrollRequest.scroll(scroll);

        SearchResponse searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
        //   getHits():
        //   getScrollId():
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        String scrollIdNew = searchResponse.getScrollId();

        if (searchHits == null || searchHits.length <= 0) {
            //
            clearClient(client, scrollIdNew);
            log.warning("scroll is close caused by no searchHits found");
        }

        return searchResponse;
    }

    private boolean clearClient(RestHighLevelClient client, String scrollId) {
        boolean isSuccess = true;
        try {
            ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
            clearScrollRequest.addScrollId(scrollId);
            ClearScrollResponse clearScrollResponse = client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
            return clearScrollResponse.isSucceeded();
        } catch (IOException e) {
            log.warning("clint close failure!");
        }
        return isSuccess;
    }


}
